﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IProjectFileExtensions.cs" company="StyleCop for ReSharper Development Team">
//   Copyright (c) StyleCop for ReSharper Development Team. All rights reserved.
// </copyright>
// <summary>
//   Extension methods for IProjectFile types.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace JetBrains.ProjectModel
{
    #region Using Directives

    using System;
    using System.Xml;

    #endregion

    /// <summary>
    /// Extension methods for IProjectFile types.
    /// </summary>
    public static class IProjectFileExtensions
    {
        #region Public Methods

        /// <summary>
        /// Returns true if the project file has been excluded from stylecop in the csproj file.
        /// </summary>
        /// <param name="projectFile">
        /// The IProjectFile to check.
        /// </param>
        /// <returns>
        /// True if its been excluded.
        /// </returns>
        public static bool ProjectFileIsExcludedFromStyleCop(this IProjectFile projectFile)
        {
            if (projectFile == null)
            {
                return false;
            }

            var project = projectFile.GetProject();

            if (project == null)
            {
                return false;
            }

            if (project.ProjectFile == null)
            {
                return false;
            }

            try
            {
                var xmlDocument = new XmlDocument();

                var relativePathToCsFile = projectFile.Location.ConvertToRelativePath(project.Location).ToString();

                xmlDocument.Load(project.ProjectFile.Location.FullPath);

                var namespaceManager = new XmlNamespaceManager(xmlDocument.NameTable);
                namespaceManager.AddNamespace("a", "http://schemas.microsoft.com/developer/msbuild/2003");
                var xmlNode = xmlDocument.SelectSingleNode(String.Format("//a:Project/a:ItemGroup/a:Compile[@Include='{0}'][a:ExcludeFromStyleCop='true']", relativePathToCsFile), namespaceManager);
                if (xmlNode != null)
                {
                    return true;
                }
            }
            catch
            {
                return false;
            }

            return false;
        }

        #endregion
    }
}